import { create } from '@inottn/miniquest'


import { config } from '@/config/axios/config'
import { getAccessToken, login } from '@/utils/auth'

const { result_code, base_url, request_timeout } = config

let axiosCreateParmater = {
  timeout: request_timeout, // 请求超时时间
  withCredentials: false, // 禁用 Cookie 等信息

  validateStatus: function (status) {
    return status >= 200 && status <= 500 // 这是默认配置
  }
}

if (uni.getSystemInfoSync().uniPlatform != 'web') {
  axiosCreateParmater.baseURL = base_url
} else {
  axiosCreateParmater.baseURL = '/useProxy'
}
const service = create(axiosCreateParmater)

service.interceptors.request.use(
  (config) => {
    config.headers = {
      Authorization: 'Bearer ' + getAccessToken()
    }
    return config
  },
  (error) => {
    return Promise.reject(error)
  }
)

const refreshToken = async () => {
  await login()
}
// response 拦截器
service.interceptors.response.use(async (response) => {
  const { data, statusCode } = response
  const config = response.config

  if (!data) {
    // 返回“[HTTP]请求没有返回值”;
    throw new Error()
  }
  // 未设置状态码则默认成功状态
  const code = statusCode
  // 二进制数据则直接返回
  if (
    response.config.responseType === 'blob' ||
    response.config.responseType === 'arraybuffer'
  ) {
    return data
  }
  // 获取错误信息
  const msg = data.message
  if (code === 401 || code === 403) {
    // 如果未认证，并且未进行刷新令牌，说明可能是访问令牌过期了
    // await refreshToken();

    uni.navigateTo({
      url: '/pages/login/index'
    })
  } else if (code === 500) {
    return Promise.reject(new Error(msg))
  } else if (code === 901) {
    return Promise.reject(new Error(msg))
  } else if (code !== 200) {
    if (msg === '无效的刷新令牌') {
      // hard coding：忽略这个提示，直接登出
      console.log(msg)
    }
    return Promise.reject('error')
  } else {
    return data
  }
})

export { service }
